var Marketplace = function() {

};

Marketplace.prototype = {
	//base : 'http://203.189.170.43/mpj2mobile',
	base : 'http://localhost:8080/mpj2',
	apiBase: "http://203.189.170.43",
	//apiUrl : "http://203.189.170.43/mpj2/jsp/sys/Sf_render.jsp",
	apiUrl : 'http://localhost:8080/mpj2/servlet/ForwardingServlet.do',
	//loginStatus:'N',
	marketplace : this,

	init : function() {
		return this;
	},
	isLogin : function() {
		//return this.loginStatus == "Y";

		var loginStatus = sessionStorage.getItem("loginStatus");
		if (loginStatus == "Y") {
			return true;
		}
		return false;
	},

	setIsLogin : function(status) {
		sessionStorage.setItem("loginStatus", status);
	},

	/**
	 * 设置地区.
	 * @param id - 地区ID
	 * @param name - 地区名称
	 */
	setDistrict : function(id , name) {
		sessionStorage.setItem("district.id", id);
		sessionStorage.setItem("district.name", name);
	},

	/**
	* 获取地区.
	*/
	getDistrict : function() {
		var id = sessionStorage.getItem("district.id");
		var name = sessionStorage.getItem("district.name");

		var district = {
			id   : id,
			name : name
		};

		return district;
	},

	/**
	 * 是否选择地区.
	 */
	isSelectDistrict : function () {
		if (this.isLogin()) {
			return true;
		}
		var district = this.getDistrict();

		if (district.id) {
			return true;
		} else {
			return false;
		}
	},
	jcart:function(){
		var arr={
			hf_s_id:"WD11",
			hf_srv_id:"Av_jcart",
		};
		getAjaxRequest(arr,function(result){
			if(result.bj_total_item_count>0){
				$('#headBox .shopcar em').show();
				$('#headBox .shopcar em').html(result.bj_total_item_count);//设置购物车中商品总数
			}else{
				$('#headBox .shopcar em').hide();
			}
			MPJ.setIsLogin(result.bs_is_login);
		}, null, true)
	},
	// 获取shop.xml数据
	getShopData : function() {
		var shopData = JSON.parse(sessionStorage.getItem("shopDas"));
		// 如果Session Storage中有数据直接返回
		if (shopData != undefined && shopData != null && shopData != "") {
			return shopData;
		}
		$.get(MPJ.apiBase+'/mpj2shop/docroot/en/shop.xml',function(result){
			var res= $.xml2json(result);
			sessionStorage.setItem('shopDas',JSON.stringify(res));
			MPJ.getShopData();
		});
	},
	getWineData:function(){
		var wineData = JSON.parse(sessionStorage.getItem("wineDas"));
		// 如果Session Storage中有数据直接返回
		if (wineData != undefined && wineData != null && wineData != "") {
			return wineData;
		}
		$.get(MPJ.apiBase+'/mpj2shop/docroot/en/winedas.xml',function(result){
			var res= $.xml2json(result);
			sessionStorage.setItem('wineDas',JSON.stringify(res));
			MPJ.getWineData();
		});
	}


};



var MPJ = new Marketplace();

var apiUrl="http://203.189.170.43/mpj2/jsp/sys/Sf_render.jsp";
var BS_RESULT = {
	OK: 'OK', // 返回成功
	ERROR:'ERROR',//返回失败
	FORCE_SELECT_DIST: 'FORCE_SELECT_DIST', // 未选择地区
	REDIRECT:'REDIRECT',//去支付
	FORCE_LOGIN:'FORCE_LOGIN' //未登录
};
var BS_IS_LOGIN={
	N:"N",//未登录
	Y:"Y" //已登录
};
$(function(){
	//getAjaxRequest({hf_s_id:"WD11",hf_srv_id:"Av_jcart",hs_set_ddc_by_dist_id:28});
	//getCartSumCount();
	if( !MPJ.isLogin() ){
		getAjaxRequest({hf_s_id:"WD11",hf_srv_id:"Zv_jset_any_ddc"}, function() {

		},null,true);
	}

	MPJ.jcart();
});


//一行数据的列表点击
$('.horizontal-list .proImg').each(function(){
	$(this).on('tap',function(){
		location.href=MPJ.base+"/pages/product/product-detail.jsp";

	})
});
$('.horizontal-list .pro-name').each(function(){
	$(this).on('tap',function(){
		location.href=MPJ.base+"/pages/product/product-detail.jsp";
	})
});

$('.horizontal-list .addCar').each(function(){
	$(this).on('tap',function(){
		dialog('Message', 'Add shopping cart success!', 1);
		var $dialog = $('#dialog');
		$dialog.show();
		$dialog.find('.comfirmBtn').one('click', function() {
			$dialog.hide();
			$dialog.remove();
		});
	});
});


//全部ajax处理  --- 有BS_RESULT返回
/**
 * 共通Ajax请求.
 * @param _data - 请求参数
 * @param callback - 回调
 * @param url - 请求地址
 * @param needSelectDist - 是否选择地址
 */
function getAjaxRequest(_data, callback, url, ignore){
	// 判断是否需要选择地址
	if (!ignore) {
		//console.log(_data);
		//alert(_data)
		//console.log(MPJ.apiUrl);
		var isSelectDist =  MPJ.isSelectDistrict();
		if (!isSelectDist) {
			window.location.href = MPJ.base + "/pages/change-delivery-location.jsp";
			return;
		}

	}

	if (!_data) {
		_data = {};
	}
	var myasync = false;
	if( _data.myasync){
		myasync = true;
		//console.log(myasync)
	}else{
		myasync = false;
	}
	delete _data.myasync
	//console.log(_data);
	if (!url) {
		url = MPJ.apiUrl;

		//url = apiUrl;
	}
	_data.url = encodeURI(apiUrl);

	$.ajax({
		type:"get",
		//url: apiUrl,
		url: url,
		dataType:"json",
		async:myasync,
		data:_data,
		success:function(result){
			//console.log(result)

			if(result.bs_result != undefined){
				if (result.bs_result == BS_RESULT.OK) {
					if (callback) {
						callback(result);
					}
				} else if (result.bs_result == BS_RESULT.ERROR) {
					if (callback) {
						callback(result);
					}
				} else if (result.bs_result == BS_RESULT.FORCE_SELECT_DIST) {
					if(location.href == MPJ.base+"/pages/change-delivery-location.jsp"){
					} else {
						//location.href=MPJ.base+"/pages/change-delivery-location.jsp";
					}
				} else if(result.bs_result == BS_RESULT.REDIRECT) {
					//location.href=
				} else if(result.bs_result == BS_RESULT.FORCE_LOGIN){
					var redirectUrl = encodeURI(location.href);
					location.href = MPJ.base + "/pages/login.jsp?redirectUrl=" + redirectUrl;
				} else {
					console.log("未知状态:" + result.bs_result);
				}
			}else{

				callback(result);
				if (result.bs_is_login != undefined ) {
					if (callback) {
						callback(result);
					}
				}

			}

		},
		error:function(err){
			//console.log(err);
		}
	});
}


//全部ajax处理 --- 没有BS_RESULT返回
function getNoResultAjaxRequest(_data, callback){
	_data.url = encodeURI(apiUrl);
	$.ajax({
		type:"get",
		url: MPJ.apiUrl + "",
		dataType:"json",
		async:true,
		data:_data,
		success:function(result){
			if (callback) {
				callback(result);
			}

		},
		error:function(err){
			//console.log(err);
		}
	});
}
function sessionStorageRemoveAll(arr) {
	var len = arr.length;
	if (len > 0) {
		for ( var i = 0; i<len; i++) {
			sessionStorage.removeItem(arr[i]);
		}
	}
}
//接口没返回数据时的展示
var no_result='<div class="no-result">'+
		'<p>No results were found</p>'+
		'</div>';

//移除arr中value为valueToDelete的元素，同时移除arr1中与该元素相同下标的元素
function deleteByValue(arr,valueToDelete,arr1){
	var ret = $.grep(arr,function(value,i){
		return value != valueToDelete;
	});
	var n = arr.indexOf(valueToDelete);
	if(n!=-1){
		arr1.splice(n,1);
	}
	return ret;
}



//获取购物车中商品的总数量
function  getCartSumCount(){
	MPJ.jcart();
}


$('.vertical-list li').each(function() {
	var $this = $(this);
	$this.off();
});


//判断价格小数部分，不满两位则添0
function getPrice(price){
	var place_price = '' ;
	if( price.toString().indexOf(",") > 0 ){
		place_price=price.toString().replace(/,/g,'');
	}else{
		place_price=price;
	}
	var result = parseFloat(place_price).toFixed(2);
	return result;
}